/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { useCallback, useState, useEffect } from 'react';
import PageHeaderLayout from '@/layouts/PageHeaderLayout';
import { connect } from 'dva';
import { Form, Row, Col, Button, message, List } from 'antd';
import { useDebounceFn } from 'ahooks';
import { debounce } from 'lodash';
import { copy } from '@/utils/utils';
import styles from './style.less';

const YzScreenManagement = Form.create()(({ dispatch, loading, generating }) => {
  const [list, setList] = useState([]);
  const [linkAndPassword, setLinkAndPassword] = useState({});

  const onCopy = debounce(
    ({ link, password }) => {
      const str = `${link}  密码：${password}`;
      copy(str, copied => {
        if (copied) {
          message.success('链接、密码复制成功！');
        } else {
          message.warning('复制失败，请手动复制！');
        }
      });
    },
    300,
    {
      leading: true,
      trailing: false,
    },
  );

  /**
   * 重置密码
   *  */
  const { run } = useDebounceFn(
    () => {
      // 生成链接及密码
      dispatch({
        type: 'bigScreen/generatePsw',
      }).then(res => {
        const { link, password } = res;
        setLinkAndPassword({ link, password });
      });
    },
    {
      wait: 1000,
      leading: true,
      trailing: false,
    },
  );

  /**
   * 获取登录用户列表及分享的链接和密码
   *  */
  const getList = useCallback(
    () =>
      new Promise(resolve => {
        dispatch({
          type: 'bigScreen/getScreenLoginUser',
        }).then(res => {
          const { list: userList, link, password } = res;
          setList(userList);
          setLinkAndPassword({ link, password });
          resolve(password);
        });
      }),
    [dispatch],
  );

  useEffect(
    () => {
      getList().then(password => {
        if (!password) {
          run();
        }
      });
    },
    [getList],
  );

  return (
    <PageHeaderLayout title="数据大屏">
      <div className={styles.main}>
        <Row type="flex" align="middle" gutter={[10, 0]} style={{ marginBottom: 24 }}>
          <Col>
            访问链接：
            {linkAndPassword.link ? (
              <a href={linkAndPassword.link} target="_blank" rel="noreferrer">
                {linkAndPassword.link}
              </a>
            ) : (
              '暂无数据'
            )}
          </Col>
          <Col>
            密码：
            {linkAndPassword.password || '暂无数据'}
          </Col>
          <Col>
            <Button type="primary" onClick={() => onCopy(linkAndPassword)}>
              复制
            </Button>
          </Col>
          <Col>
            <Button type="primary" onClick={run} loading={generating}>
              重置密码
            </Button>
          </Col>
        </Row>
        <List
          loading={loading}
          bordered
          header="访问设备"
          dataSource={list}
          renderItem={item => {
            const { login_ip, login_at } = item;
            return (
              <List.Item>
                <Row gutter={[0, 5]}>
                  <Col>{login_ip}</Col>
                  <Col style={{ color: '#bdbdbd' }}>
                    上次登录时间：
                    {login_at}
                  </Col>
                </Row>
              </List.Item>
            );
          }}
        />
      </div>
    </PageHeaderLayout>
  );
});

export default connect(({ loading }) => ({
  loading: loading.effects['bigScreen/getScreenLoginUser'],
  generating: loading.effects['bigScreen/generatePsw'],
}))(React.memo(YzScreenManagement));
